const path = require('path');
const fs = require('fs');
const goodsModel = require('../models/goodsModel');
const mongoose = require('mongoose');
const image = require('../utils/images');
const fileHandle = files => {
    if (files) {
        files.forEach((item, index) => {
            const oldFile = path.join(__dirname, '../public/upload/tmp') + `/${item}`;
            const newFile = path.join(__dirname, '../public/upload/goods') + `/${item}`;
            fs.rename(oldFile, newFile, (err) => {
                if (err) {
                    console.log('图片异常');
                } else {
                    if (index === 0) {
                        image.shrink(newFile); // 给第一张生成缩略图
                    }
                }
            })
            files[index] = `/goods/${item}`;
        });
    }
}
const create = async(ctx, next) => {
    try {
        const req = ctx.request.body;
        const data = Object.assign({
            createDate: new Date(),
            status: 1,
            createUser: ctx.state.user.username
        }, req);
        fileHandle(req.banner);
        fileHandle(req.details);
        data.thumbnail = image.fileNameFormat(req.banner[0], '-small');
		data.repertory = 0;
        if (data.skuList) {
            data.skuList.forEach(item => {
                /* if (!item.discountPrice) {
                    item.discountPrice = item.originalPrice;
                } */
				data.repertory += item.repertory;
            })
        }
        if (data._id) {
            await goodsModel.update({
                _id: data._id
            }, data);
        } else {
			delete data._id;
            await goodsModel.create(data)
        }
        ctx.body = {
            code: 1,
            msg: '操作成功！'
        };
    } catch (e) {
        ctx.body = {
            code: -1,
            msg: e.message,
            data: {}
        };
    }
}

const updRepertory = async({ id, skuId, count }) => {
    const result = await goodsModel.findById(id);
    if (result) {
        const items = result.skuList.filter(sku => sku._id == skuId);
        if (items.length) {
            const sku = items[0];
            if (sku.repertory < count) {
                throw new Error('库存不足');
            } else {
				result.saleVolume += count;
				result.repertory -= count;
                sku.repertory -= count;
                try {
                    await goodsModel.updateOne({
                        _id: id
                    }, result);
                } catch (e) {
                    throw new Error('库存更新失败');
                }
            }
        }
    }
}

const findByIds = async ids => {
	
    return await goodsModel.find({
        _id: {
            $in: ids.map(item => mongoose.Types.ObjectId(item))
        }
    });
}

const findById = async(ctx, next) => {
    try {
        const id = ctx.params.id;
        const result = await goodsModel.findById(id);
        ctx.body = {
            code: 1,
            data: result
        };
    } catch (e) {
        ctx.body = {
            code: -1,
            msg: e.message
        };
    }
}

const findAllName = async(ctx, next) => {
    const query = ctx.request.query;
    const name = query.name;
    const condition = {
        status: {
            $eq: 1
        }
    };
    if (name) {
        condition.name = {
            $regex: name
        }
    }
    const result = await goodsModel.find(condition, { name: 1, _id: 1 }, {
        sort: {
            createDate: 'desc'
        }
    });
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const find = async(ctx, next) => {
    const {name, createDate, saleVolume, repertory, classify} = ctx.request.query;
	const sort = {};
    const condition = {
        status: 1
    };
    if (name) {
        condition.name = {
            $regex: name
        }
    }
	if (saleVolume) {
	    sort.saleVolume = saleVolume == 1 ? 'desc' : 'asc';
	}
	if (createDate) {
	    sort.createDate = createDate == 1 ? 'desc' : 'asc';
	}
	if (repertory) {
	    sort.repertory = repertory == 1 ? 'desc' : 'asc';
	}
    if (classify) {
        condition.classify = {
            $elemMatch: {
                $eq: classify
            }
        }
    }
	console.log(sort);
    const result = await goodsModel.find(condition, null, {
        sort
    });
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const update = async(ctx, next) => {
    const req = ctx.request.body;
    req.updateUser = ctx.state.user.username;
    const result = await goodsModel.update({
        _id: req._id
    }, req);
    if (result) {
        ctx.body = {
            code: 1,
            msg: '修改成功！',
            data: {}
        };
    }
}

module.exports = {
    create,
    find,
    update,
    findById,
    findByIds,
    updRepertory,
    findAllName
};